# -*- coding: utf-8 -*-
#coding=utf-8

import os
import config
from action.admin.base import adminAction
from model.company import company
from model.category import category
from model.image import image
from model.user import user
from model.album import album

'''
Admin controller: producing company administration views.
'''
class refererAction(adminAction):
    def __init__(self, name = '公司管理'):
        adminAction.__init__(self, name)

    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'delete':
            return self.delete()
        elif name == 'add':
            return self.add()
        elif name == 'edit':
            return self.edit()
        elif name == 'listForBatchDel':
            return self.listForBatchDel()
        else:
            return self.notFound()

        return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'update':
            return self.update()
        elif name == 'deleteBatch':
            return self.deleteBatch()
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        companyObj = company()
        listData = companyObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        companyList = companyObj.getList('*', condition, 'id asc', str(offset) + ',' + str(count))
        pageString = self.getPageStr('/admin/company/list', page, count, totalCount)
        self.privData['COMPANY_LIST'] = companyList
        self.privData['PAGE_STRING'] = pageString
        return self.display('companyList')


    def listForBatchDel(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        companyObj = company()
        listData = companyObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        companyList = companyObj.getList('*', condition, 'id asc', str(offset) + ',' + str(count))
        pageString = self.getPageStr('/admin/company/list', page, count, totalCount)
        self.privData['COMPANY_LIST'] = companyList
        self.privData['PAGE_STRING'] = pageString

        categoryList = category().getList('*', condition)
        self.privData['CATEGORY_LIST'] = {}
        for i in categoryList:    
            self.privData['CATEGORY_LIST'][i['id']] = i['name']

        return self.display('companyBatchDel')

    def delete(self):
        inputParams = self.getInput()

        try:
            condition={'id': inputParams['id']}
            company().delete(condition)
        except Exception, e:
            return self.success(msg='公司删除失败: %s' % e, url=self.makeUrl('/admin/company/list'))

        return self.success(msg='公司删除成功', url=self.makeUrl('/admin/company/list'))

    def deleteBatch(self):
        inputParams = self.getInput()
        try:
            condition = ' id IN (' + inputParams['delitems'] +')'
            company().delete(condition)
        except Exception, e:
            return self.error(msg='对象删除失败: %s' % e, url=self.makeUrl('/admin/company/list'))

        return self.success(msg='对象删除成功', url=self.makeUrl('/admin/company/list'))

    def edit(self):
        inputParams = self.getInput()

        condition={'id': inputParams['id']}
        companyObj = company().getOne('*', condition)
        if not companyObj:
            return self.error(msg = '该公司不存在', url=self.makeUrl('/admin/company/list'))

        condition = {}
        categoryList = category().getList('*', condition)

        self.privData['CATEGORY_LIST'] = {}
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = companyObj["logo"]
        self.privData['SUBMIT_NAME'] = "thumbnail"

        condition = {'id': companyObj['owner']}
        userObj = user().getOne('nickname', condition)
        self.privData['OWNER'] = userObj['nickname']
        self.privData['COMPANY'] = companyObj

        return self.display('companyEdit')

    def update(self):
        inputParams= self.getInput()  
        data = {
            'email':        inputParams['email'],
            'name':         inputParams['name'],
            'owner':        inputParams['owner'],
            'fixedphone':   inputParams['fixedphone'],
            'cellphone':    inputParams['cellphone'],
            'faxno':        inputParams['faxno'],
            'address':      inputParams['address'],
            'postcode':     inputParams['postcode'],
            'contact':      inputParams['contact'],
            'category':     int(inputParams['category']),
            'desc':         inputParams['desc'],
            'logo':         int(inputParams['thumbnail']),
        }
        try:
            condition={'id': inputParams['id']}
            company().update(data, condition)
        except Exception, e:
            return self.error(msg = '公司修改失败: %s' % e, url=self.makeUrl('/admin/company/list'))

        return self.success('公司修改成功', url=self.makeUrl('/admin/company/list'))

    def add(self):
        condition = {}
        categoryList = category().getList('*', condition)

        self.privData['CATEGORY_LIST'] = {}
        for item in categoryList:
            self.privData['CATEGORY_LIST'][item['id']] = item['name']

        userList = user().getList('*', condition)
        self.privData['USER_LIST'] = {}
        for item in userList:
            self.privData['USER_LIST'][item['id']] = item['nickname']

        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = 1
        self.privData['SUBMIT_NAME'] = "thumbnail"

        return self.display('companyAdd')

    def save(self):
        inputParams= self.getInput()  
        data = {
            'email':        inputParams['email'],
            'name':         inputParams['name'],
            'owner':        inputParams['owner'],
            'fixedphone':   inputParams['fixedphone'],
            'cellphone':    inputParams['cellphone'],
            'faxno':        inputParams['faxno'],
            'address':      inputParams['address'],
            'postcode':     inputParams['postcode'],
            'contact':      inputParams['contact'],
            'category':     int(inputParams['category']),
            'desc':         inputParams['desc'],
            'logo':         int(inputParams['thumbnail']),
        }
        try:
            company().insert(data)
        except Exception, e:
            return self.error(msg = '公司保存失败: %s' % e, url=self.makeUrl('/admin/company/list'))

        return self.success('公司保存成功', url=self.makeUrl('/admin/company/list'))

